package com.yyr.spring_boot.modules.test.service.impl;

import com.yyr.spring_boot.modules.common.vo.Search;
import com.yyr.spring_boot.modules.test.entity.Student;
import com.yyr.spring_boot.modules.common.vo.Result;
import com.yyr.spring_boot.modules.test.dao.StudentDao;
import com.yyr.spring_boot.modules.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    @Override
    @Transactional
    public Result<Student> insertStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code,
                "Insert success", student);
    }

    @Override
    @Transactional
    public Result<Student> updateStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code,
                "Update success", student);
    }

    @Override
    @Transactional
    public Result<Object> deleteStudentById(int id) {
        studentDao.deleteById(id);
        return new Result<>(Result.ResultStatus.SUCCESS.code,
                "Delete success");
    }

    @Override
    public Student getStudentById(int id) {
//        return studentDao.getById(id);
        return studentDao.getStudentById(id);
    }

    @Override
    public Page getStudentsBySearch(Search search) {
        //初始化查询对象
        search.init();

        //分页和排序功能
        Sort sort = Sort.by(
                search.getDirection()
                        .toLowerCase()
                        .equals("asc") ?
                        Sort.Direction.ASC :
                        Sort.Direction.DESC,
                search.getSort()
        );
        PageRequest pageable = PageRequest
                .of(search.getCurrentPage(),
                        search.getPageSize(),
                        sort);

        //查询模板
        Student student = new Student();
        student.setStudentName(search.getKeyword());
        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withMatcher("studentName", match -> match.contains())
                .withIgnorePaths("id");
        //根据实体 bean 属性以及设定的模板匹配器规则，到数据库查询
        //设置查询条件
        Example<Student> example = Example.of(student, matcher);

        return studentDao.findAll(example, pageable);
    }

    @Override
    public List<Student> getStudentByStudentName(String studentName) {
        return Optional
                .of(studentDao.findByStudentName(studentName))
                .orElse(Collections.emptyList());
    }


}
